<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen v-model="showDialog" :title="title">
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter v-if="!props.orderId" :filter-list="filterInfo.list">
              <template v-slot:filter-addRow>
                <el-button @click="addRow">新增行</el-button>
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                <page-table
                  ref="table"
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tabIndex="false"
                  :check-box="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-businessDate="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.businessDate`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择日期',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-date-picker
                        v-model="scope.row.businessDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择日期"
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.businessDate`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-assetCode="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.assetCode`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择资产卡片号',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input
                        :ref="'batchRef' + scope.$index"
                        class="not-mongolia"
                        placeholder="请选择资产卡片号"
                        v-model="scope.row.assetCode"
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.assetCode`,
                            'tableForm'
                          )
                        "
                      >
                        <template #append>
                          <div
                            class="el-input-search"
                            @click="addAsset(scope.row, scope.$index)"
                          >
                            <el-icon style="vertical-align: middle">
                              <MoreFilled />
                            </el-icon>
                          </div>
                        </template>
                      </el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-depreciationCost="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.depreciationCost`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.depreciationCost"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.depreciationCost`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-repairCost="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.repairCost`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.repairCost"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.repairCost`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-maintenanceCost="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.maintenanceCost`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.maintenanceCost"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.maintenanceCost`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-materialCost="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.materialCost`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.materialCost"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.materialCost`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-medicineCost="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.medicineCost`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.medicineCost"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.medicineCost`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-personnelCost="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.personnelCost`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.personnelCost"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.personnelCost`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-houseDepreciationCost="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.houseDepreciationCost`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.houseDepreciationCost"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.houseDepreciationCost`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-utilitiesCost="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.utilitiesCost`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.utilitiesCost"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.utilitiesCost`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template
                    v-for="(item, index) in tableTitle"
                    :key="index"
                    v-slot:[getSlotName(item)]="scope"
                  >
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.${item.value}`"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row[item.value]"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.${item.value}`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 选择资产 -->
    <SelectProduct
      v-if="selectAssetInfo.visible"
      v-model:showDialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query"
      :api="selectAssetInfo.api"
      :highlightRow="true"
      :check-box="!orderId"
      :fieldList="assetFieldList"
      title="可选资产"
      placeholder="编码\名称"
      @callback="callBackAsset"
    />
  </div>
</template>

<script setup>
const SelectProduct = defineAsyncComponent(() =>
  import('@/views/asset/analy/components/SelectProduct')
)
import {
  getAnalysisPlanAndAssetPage,
  postCostDetail,
  getCostDetailTitle,
} from '@/api/asset'
const { proxy } = getCurrentInstance()
const emits = defineEmits()

const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  orderId: {
    type: [Number, String],
  },
})
const selectAssetInfo = ref({
  visible: false,
  query: {
    keyword: '',
    sort: null,
  },
  row: {},
  api: getAnalysisPlanAndAssetPage,
  index: 0,
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'addRow' },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [
    {
      randomNumber: new Date().getTime(),
    },
  ],
  tabIndex: 0,
  selections: [],
  fieldList: [
    {
      label: '支出日期',
      value: 'businessDate',
      type: 'slot',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'slot',
      width: '140px',
    },
    { label: '资产名称', value: 'assetName' },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '设备折旧费用', value: 'depreciationCost' },
    { label: '维修费用', value: 'repairCost', type: 'slot' },
    { label: '养护费用', value: 'maintenanceCost', type: 'slot' },
    { label: '耗材费用', value: 'materialCost', type: 'slot' },
    { label: '药品费用', value: 'medicineCost', type: 'slot' },
    { label: '人工费用', value: 'personnelCost', type: 'slot' },
    { label: '房屋折旧费', value: 'houseDepreciationCost', type: 'slot' },
    { label: '水电费用', value: 'utilitiesCost', type: 'slot' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '60',
    btList: [
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: !props.orderId,
      },
    ],
  },
})
const assetFieldList = ref([
  {
    label: '资产卡片号',
    value: 'assetCode',
  },
  {
    label: '资产名称',
    value: 'assetName',
  },
  {
    label: '规格',
    value: 'standard',
  },
  {
    label: '厂家',
    value: 'brandName',
  },
])
const tableTitle = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

onMounted(() => {
  getTableFieldList()
})

function getTableFieldList() {
  getCostDetailTitle().then((res) => {
    if (res.success && res.data) {
      for (let k in res.data) {
        tableInfo.value.fieldList.push({
          label: res.data[k],
          value: k,
          type: 'slot',
        })
        tableTitle.value.push({
          label: res.data[k],
          value: k,
        })
      }
    }
  })
}
function getSlotName(item) {
  return 'col-' + item.value
}
function changeValidate(value, str, ref) {
  setTimeout(() => {
    proxy.$refs[ref].clearValidate(str)
  }, 30)
}
function addAsset(row, index) {
  selectAssetInfo.value.row = row
  selectAssetInfo.value.index = index
  selectAssetInfo.value.visible = true
}
function callBackAsset(data) {
  data.forEach((item, index) => {
    let newObj = {
      assetCode: item.assetCode,
      assetName: item.assetName,
      standard: item.standard,
      brandName: item.brandName,
      standard: item.standard,
      planNo: item.planNo,
      planName: item.planName,
      analysisPlanId: item.analysisPlanId,
      assetId: item.assetId,
    }
    if (index === 0) {
      tableInfo.value.data[selectAssetInfo.value.index] = {
        ...selectAssetInfo.value.row,
        ...newObj,
      }
    } else {
      tableInfo.value.data.splice(
        selectAssetInfo.value.index + index,
        0,
        newObj
      )
    }
  })
  selectAssetInfo.value.visible = false
  // const index = selectAssetInfo.value.index
  // const newObj = {
  //   assetCode: data.assetCode,
  //   assetName: data.assetName,
  //   standard: data.standard,
  //   brandName: data.brandName,
  //   standard: data.standard,
  //   planNo: data.planNo,
  //   planName: data.planName,
  //   analysisPlanId: data.analysisPlanId,
  //   assetId: data.assetId,
  // }
  // tableInfo.value.data[index] = {
  //   ...tableInfo.value.data[index],
  //   ...newObj,
  // }
  // selectAssetInfo.value.visible = false
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//新增行
function addRow() {
  const randomNumber = new Date().getTime()
  tableInfo.value.data.push({
    randomNumber: randomNumber,
  })
}
function removeProduct(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row != selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        const tempData = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
        tableInfo.value.data = tempData
      })
  }
}
// 触发事件
function save() {
  if (!tableInfo.value.data || tableInfo.value.data.length === 0) {
    proxy.$message.warning('请添加支出明细！')
    return
  }
  tableInfo.value.data.forEach((item) => {
    item.titleMap = {}
    tableTitle.value.forEach((el) => {
      item.titleMap[el.value] = item[el.value]
    })
  })
  proxy.$refs.tableForm.validate((valid) => {
    if (valid) {
      postCostDetail(tableInfo.value.data).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          proxy.$emit('returnModify', false)
        }
      })
    } else {
      proxy.$message.warning('请按照提示输入正确数据')
    }
  })
}
</script>

<style scoped lang="scss">
.el-input-search {
  width: 100%;
  height: 100%;
}
</style>
